package com.example.taobaolianmeng.presenter.impl;

import com.example.taobaolianmeng.model.Api;
import com.example.taobaolianmeng.model.domain.Histories;
import com.example.taobaolianmeng.model.domain.SearchRecommend;
import com.example.taobaolianmeng.model.domain.SearchResult;
import com.example.taobaolianmeng.presenter.ISearchPresenter;
import com.example.taobaolianmeng.presenter.ISelectedPagePresenter;
import com.example.taobaolianmeng.utils.JsonCacheUtil;
import com.example.taobaolianmeng.utils.RetrofitManager;
import com.example.taobaolianmeng.view.ISearchPageCallback;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class SearchPagePresenterImpl implements ISearchPresenter {

    private final Api mApi;
    private ISearchPageCallback mSearchViewCallback =null;
    private String mCurrentKeyword = null;
    private final JsonCacheUtil mJsonCacheUtil;

    //RetrofitManager 已经设为单例每次使用 要先用构造方法实现
    public SearchPagePresenterImpl() {
        RetrofitManager instance = RetrofitManager.getInstance();
        Retrofit retrofit = instance.getRetrofit();
        mApi = retrofit.create(Api.class);
        //因为是单例只会创建一次 ，所有可以放心使用
        mJsonCacheUtil = JsonCacheUtil.getInstance();

    }

    @Override
    public void getHistories() {
        Histories histories = mJsonCacheUtil.getValue(KEY_HISTORIES, Histories.class);
        if(mSearchViewCallback!=null){
            mSearchViewCallback.onHistoriesLoaded(histories);
        }
    }

    @Override
    public void delHistories() {
        mJsonCacheUtil.delCache(KEY_HISTORIES);
        if(mSearchViewCallback != null) {
            mSearchViewCallback.onHistoriesDeleted();
        }
    }

    public static  final String KEY_HISTORIES = "key_histories";
    public static  final  int DEFAULT_HISTORIES_SIZE = 10;
    private int mHistoriesMaxSize = DEFAULT_HISTORIES_SIZE;
    //添加历史记录
    private void saveHistory(String history){
//        this.delHistories();    //手动清除缓存（调试）
        Histories histories = mJsonCacheUtil.getValue(KEY_HISTORIES,Histories.class);
        //如果说已经在了，就干掉，然后再添加
        List<String> historiesList = null;
        if(histories != null && histories.getHistories() != null) {
            historiesList = histories.getHistories();
            if(historiesList.contains(history)) {
                historiesList.remove(history);
            }
        }
        //去重完成
        //处理没有数据的情况
        if(historiesList == null) {
            historiesList = new ArrayList<>();
        }
        if(histories == null) {
            histories = new Histories();
        }
        histories.setHistories(historiesList);
        //对个数进行限制
        if(historiesList.size() > mHistoriesMaxSize) {
            historiesList = historiesList.subList(0,mHistoriesMaxSize);
        }
        //添加记录
        historiesList.add(history);
        //保存记录
        mJsonCacheUtil.saveCache(KEY_HISTORIES,histories);

    }

    public static final int DEFAULT_PAGE = 0;
    //s搜索当前页
    private int mCurrentPage = DEFAULT_PAGE;

    @Override
    public void doSearch(String keyword) {
        if(mCurrentKeyword == null || !mCurrentKeyword.equals(keyword)) {
            //TODO
            this.saveHistory(keyword);
            this.mCurrentKeyword = keyword;
        }
        //跟新ui状态
        if (mSearchViewCallback != null) {
            mSearchViewCallback.onLoading();
        }
        Call<SearchResult> task = mApi.doSearch(mCurrentPage, keyword);
        task.enqueue(new Callback<SearchResult>() {
            @Override
            public void onResponse(Call<SearchResult> call, Response<SearchResult> response) {
                int code = response.code();
                if(code == HttpURLConnection.HTTP_OK){
                    handleSearchResult(response.body());
                }else{
                    onError();
                }
            }

            @Override
            public void onFailure(Call<SearchResult> call, Throwable t) {
                onError();
            }
        });
    }

    private void onError() {
        if (mSearchViewCallback != null) {
            mSearchViewCallback.onNetworkError();
        }
    }

    private  boolean isResultEmpty(SearchResult result){
        try{
            return result == null || result.getData().getTbk_dg_material_optional_response().getResult_list().getMap_data().size()== 0;
        }catch (Exception e){
            return  false;
        }
    }

    private void handleSearchResult(SearchResult result) {
        if(mSearchViewCallback !=null){
            if(isResultEmpty(result)){
                //数据为空
                mSearchViewCallback.onEmpty();
            }else{
                mSearchViewCallback.onSearchSuccess(result);
            }
        }
    }

    @Override
    public void research() {
        if(mCurrentKeyword == null){
            if(mSearchViewCallback !=null){
                mSearchViewCallback.onEmpty();
            }
        }else{
            //做搜索
            this.doSearch(mCurrentKeyword);
        }
    }

    @Override
    public void loaderMore() {
        mCurrentPage++;
        //搜索
        if(mCurrentKeyword ==null){
            if (mSearchViewCallback !=null) {
                mSearchViewCallback.onEmpty();
            }
        }else{
            //搜索
            doSearchMore();
        }
    }

    private void doSearchMore() {
        Call<SearchResult> task = mApi.doSearch(mCurrentPage, mCurrentKeyword);
        task.enqueue(new Callback<SearchResult>() {
            @Override
            public void onResponse(Call<SearchResult> call, Response<SearchResult> response) {
                int code = response.code();
                if(code == HttpURLConnection.HTTP_OK){
                    handleMoreSearchResult(response.body());
                }else{
                    onLoadMoreError();
                }
            }

            @Override
            public void onFailure(Call<SearchResult> call, Throwable t) {
                onLoadMoreError();
            }
        });
    }

    /*
    * 处理加载更多的结果
    * */
    private void handleMoreSearchResult(SearchResult result) {
        if(mSearchViewCallback !=null){
            if(isResultEmpty(result)){
                //数据为空
                mSearchViewCallback.onMoreLoadedEmpty();
            }else{
                mSearchViewCallback.onMoreLoaded(result);
            }
        }
    }

    /*
    * 加载更多失败
    * */

    private void onLoadMoreError() {
        mCurrentPage--;
        if (mSearchViewCallback != null) {
            mSearchViewCallback.onMoreLoadedError();
        }
    }

    @Override
    public void getRecommendWords() {
        Call<SearchRecommend> task = mApi.getRecommendWords();
        task.enqueue(new Callback<SearchRecommend>() {
            @Override
            public void onResponse(Call<SearchRecommend> call, Response<SearchRecommend> response) {
                int code = response.code();
                if(code== HttpURLConnection.HTTP_OK){
                    //处理
                    if (mSearchViewCallback != null) {
                        mSearchViewCallback.onRecommendWordsLoaded(response.body().getData());
                    }
                }
            }

            @Override
            public void onFailure(Call<SearchRecommend> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    @Override
    public void registerViewCallback(ISearchPageCallback callBack) {
        this.mSearchViewCallback = callBack;
    }

    @Override
    public void unregisterViewCallback(ISearchPageCallback callBack) {
        this.mSearchViewCallback = null;
    }
}
